//待补充
$NG.AllReady(function (page, { useDataIndexChange, useUpdateRow, useUpdateRows, useValuesChange, useBeforeClick, useClick }) {
    const userInfo = $NG.getUser();
    const mstform = $NG.getCmpApi("p_form_procurement_spare_m");
    const grid1 = $NG.getCmpApi("p_form_procurement_spare_d");
    // mstform.setHidden("u_phidkey",false); //设置隐藏
    const getItemValue = (itemName) => mstform.getItem(itemName).getValue();
    /**
     *@default: 初始化
     */
    if ($NG.getCmpApi("p_form_procurement_spare_m")) {
      getPtInfoByPhid();
      $NG.updateState((updater) => {
        updater.data.p_form_procurement_spare_m.setProps({
          phid_fcur: {
            value: 1,
            label: "人民币",
          },
          exchangerate: 1,
        });
      });
  
      if (page.oType == "add") {
        console.log("111");
        let generateKeyStr = generateKey().toString().replace(".", "");
        mstform.getItem("u_phidkey").setValue(generateKeyStr);
        $NG.execServer("GETuserdept", { phid: userInfo.userID }, (res) => {
          const datas = JSON.parse(res.data)[0].extendObjects;
          console.log(userInfo.userID, "userInfo.userID");
  
          console.log(datas, "GETuserdeptdatas");
          $NG.updateState((updater) => {
            updater.data.p_form_procurement_spare_m.setProps({
              u_applicant: {
                value: datas.hrid,
                label: datas.username,
              },
              u_apply_dept: {
                value: datas.dept_id,
                label: datas.deptname,
              },
            });
          });
        });
      }
    }
    /**
     *@license: 	 //表头字段变化逻辑END	//表头字段变化逻辑BEGIN
     */
    useValuesChange(async ({ args }) => {
      getPtInfoByPhid();
      let _arr = grid1.getRows();
      let _json = [];
      let lock = true;
      setTimeout(async () => {
        _arr.forEach((item) => {
          console.log(`item`, item);
          if (item.u_cost_pc) {
            _json.push({
              u_entity: mstform.getItem("u_budget_org").getValue(),
              u_account: item.u_cost_pc_EXName,
              phid_fcur: mstform.getItem("phid_fcur").getValue(),
            });
          }
        });
        if (_json.length == 0 || !mstform.getItem("u_budget_org").getValue() || !mstform.getItem("phid_fcur").getValue()) {
          lock = false;
        }
        const _data = {
          billType: "WKSD",
          phid_pc: mstform.getItem("phid_pc").getValue(),
          bill_dt: mstform.getItem("bill_dt").getValue(),
          detail: _json,
        };
        //  请求得到的数据
        if (lock) {
          const resBody = await reqAmt(_data);
          const _datas = resBody.data;
          _datas.forEach((it) => {
            _arr.forEach((item) => {
              if (item.u_cost_pc_EXName == it.account) {
                //TODO 在请求数据中查找并找到相应的数据进行对字段赋值
                item.u_balance = it.balance;
              }
            });
          });
          grid1.refreshView();
        }
      }, 300);
    }, "p_form_procurement_spare_m.phid_pc");
  
    /**
     *@function:带出项目信息
     */
    function getPtInfoByPhid() {
      if (mstform.getItem("phid_pc").getValue()) {
        $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
          const datas = JSON.parse(res.data)[0].extendObjects;
          console.log(datas, "11111111111");
          //帮助字段赋值
          $NG.updateState((updater) => {
            updater.data.p_form_procurement_spare_m.setProps({
              // u_supply_att: datas.u_supply_att, //计划完工日期
              // u_supply_name: datas.u_supply_name, //计划竣工日期
              u_pc_no: datas.pc_no, //项目编码
              u_budget_org_name: datas.budget_org_name,
              u_budget_org_no: datas.budget_org_no,
              u_dept: {
                value: datas.dept_phid,
                label: datas.dept_name,
              },
              u_division: {
                //事业部or组织
                value: datas.org_phid,
                label: datas.org_name,
              },
  
              u_regional_center: {
                //区域中心
                value: datas.regional_center_phid,
                label: datas.regional_center_name,
              },
              u_product_line: {
                //产品线
                value: datas.midwife_phid,
                label: datas.midwife_name,
              },
              u_budget_org: {
                value: datas.budget_org_phid,
                label: datas.budget_org_name,
              },
            });
          });
        });
      }
      $NG.execServer("projectSjbm", { phid: `${mstform.getItem("phid_pc").getValue()}` }, function (res) {
        try {
          const datas = JSON.parse(res.data)[0].extendObjects;
          //商机号
          mstform.getItem("u_sjh").setValue(datas.user_sjbm);
          //商机编码
          mstform.getItem("u_sjmc").setValue(datas.user_sjmc);
        } catch (error) {}
      });
    }
  
    useValuesChange(({ args }) => {
      console.log(args, "u_budget_org");
    }, "p_form_procurement_spare_m.u_budget_org");
    /**
     *@function:计算逻辑
     */
    useUpdateRow(({ args }) => {
      console.log(args[0], "分包明细表 计算");
      let row = args[0];
      if (args[0].u_cost_pc_EXName && mstform.getItem("phid_pc").getValue() && mstform.getItem("u_budget_org").getValue() && mstform.getItem("phid_fcur").getValue()) {
        const _maps = {
          billType: "WKSD",
          phid_pc: mstform.getItem("phid_pc").getValue(),
          bill_dt: mstform.getItem("bill_dt").getValue(),
          detail: [
            {
              u_entity: mstform.getItem("u_budget_org").getValue(),
              u_account: args[0].u_cost_pc_EXName,
              phid_fcur: mstform.getItem("phid_fcur").getValue(),
            },
          ],
        };
        // reqAmt(_maps);
      }
      computedV2(row);
      // 更新和刷新表格
      grid1.refreshView();
    }, "p_form_procurement_spare_d");
    useUpdateRows(({ args }) => {
      let rows = args[0];
      let total = 0;
  
      rows.forEach((item) => {
        total += item.u_amt_vat || 0; // 确保值存在且为数字
        if (item.itemid) {
          $NG.execServer("searchMasterP", { phid: item.itemid }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(datas, "xxxxxxxx");
            item.itemno = datas.itemno;
            item.spec = datas.spec;
            item.msunit = datas.msunit_phid;
            item.msunit_EXName = datas.msunit_name; //单位
            // item.u_item_sub = datas.res_bs_phid; //单位
            // item.u_item_sub_EXName = datas.res_bs_name; //单位
            grid1.refreshView();
          });
        }
      });
      mstform.getItem("u_amt_vat").setValue(total);
      console.log("Total u_amt_vat:", total);
  
      // 更新和刷新表格
      // 带物料相信息;
    }, "p_form_procurement_spare_d");
    // TODO 单行更改触发请求，赋值到金额
    useDataIndexChange(async ({ args }) => {
      if (args[0].u_cost_pc_EXName) {
        const _maps = {
          billType: "WKSD",
          phid_pc: mstform.getItem("phid_pc").getValue(),
          bill_dt: mstform.getItem("bill_dt").getValue(),
          detail: [
            {
              u_entity: mstform.getItem("u_budget_org").getValue(),
              u_account: args[0].u_budget_account,
              phid_fcur: mstform.getItem("phid_fcur").getValue(),
            },
          ],
        };
        const resBody = await reqAmt(_maps);
        const _data = resBody.data[0];
        args[0].u_balance = _data.balance;
        grid1.refreshView();
      }
    }, "u_cost_pc");
    // useDataIndexChange(async ({ args }) => {
    // 	if (args[0].u_budget_account) {
    // 		const _maps = {
    // 			billType: "WKSD",
    // 			phid_pc: mstform.getItem("phid_pc").getValue(),
    // 			bill_dt: mstform.getItem("bill_dt").getValue(),
    // 			detail: [
    // 				{
    // 					u_entity: mstform.getItem("u_budget_org").getValue(),
    // 					u_account: args[0].u_budget_account,
    // 					phid_fcur: mstform.getItem("phid_fcur").getValue(),
    // 				},
    // 			],
    // 		};
    // 		const resBody = await reqAmt(_maps);
    // 		const _data = resBody.data[0];
    // 		args[0].u_balance = _data.balance;
    // 		grid1.refreshView();
    // 	}
    // }, "u_budget_account");
  
    function computedV2(rowItem) {
      const record = rowItem;
  
      // 提供默认值并确保为数字类型，防止字符串影响计算
      const u_qty = Number(record.u_qty) || 0; // 数量，默认为 0
      const u_vat_prc = Number(record.u_vat_prc) || 0; // 含税单价，默认为 0
      const u_tax_rate = Number(record.u_tax_rate) || 0; // 税率，默认为 0
  
      // 计算不含税单价
      const u_prc = u_vat_prc / (1 + u_tax_rate);
  
      // 计算字段值
      const u_amt_vat = u_qty * u_vat_prc; // 价税合计
      const u_amt = u_qty * u_prc; // 不含税金额
      const u_tax_amt = u_amt_vat - u_amt; // 税额
      const u_amt_vat_fc = u_amt_vat; // 价税合计（与 u_amt_vat 相同）
  
      // 更新 record 对象
      Object.assign(record, {
        u_prc,
        u_amt_vat,
        u_amt,
        u_tax_amt,
        u_amt_vat_fc,
      });
    }
    async function reqAmt(datas) {
      console.log(`请求参数检查`, datas);
      const resBody = await $NG.request.post({
        url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/fiCheckBalance",
        data: JSON.stringify(datas),
        header: {
          "Content-Type": "application/json",
        },
      });
      console.log(`响应信息`, resBody);
      return resBody;
    }
    useBeforeClick(async function ({ args }) {
      (function () {})();
  
      const _arr = grid1.getRows();
      const _index = [];
      _arr.forEach((item, index) => {
        if (Number(item.u_balance) < Number(item.u_amt_vat)) {
          _index.push(index + 1);
        }
      });
      if (_index.length !== 0) {
        $NG.alert(`明细中第 ${_index.join("、")} 行中，价税合计超出余额！！`);
        return false;
      }
      return true;
    }, "save");
  
    useClick((prop) => {
      setTimeout(() => {
        console.log("");
        $NG.execServer("getPhidKey", { phidkey: mstform.getItem("u_phidkey").getValue() }, (res) => {
          mstform.getItem("u_phidkey").getValue();
          console.log(`响应信息datasssss??`);
          const datas = JSON.parse(res.data)[0].extendObjects;
          console.log("datas", datas);
          async function pushPhid() {
            const resBody = await $NG.request.post({
              url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/pushBudgetPreoccupation",
              data: JSON.stringify({ phid: datas.phid }),
              header: {
                "Content-Type": "application/json",
              },
            });
            console.log(`响应信息1111`, resBody);
            return resBody;
          }
          pushPhid();
        });
      }, 2000);
    }, "save");
  });
  function generateKey() {
    // 使用 Date.now() 获取当前时间戳
    let timestamp = Date.now();
    // 使用 Math.random() 生成一个随机数
    let random = Math.random();
    // 将时间戳和随机数组合，并转换为字符串
    let key = timestamp.toString() + random.toString();
    return key;
  }
  